import wx
import wx.grid
import talkToGoogle
import datetime
import calendar
import wx.lib.newevent
import time
import sys
from wxPython.wx import *

class Calendar():
    monthLabels = ['', '', '', '', '', '', '']
    dateLabels = ['', '', '', '', '', '', '']
    monthNames = ['','January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    def __init__(self):
        # month, day, and year are numbers in the form ##/##/####
        self.month = time.localtime()[1]
        self.day = time.localtime()[2]
        self.year = time.localtime()[0]
    def start_end_YMD(self, months, year):
      start_month = months[0]
      end_month = months[-1]
      start_year = year
      if end_month == 1:
          end_year = start_year + 1
      else:
          end_year = start_year
      start_day = int(Calendar.dateLabels[0])
      if int(Calendar.dateLabels[6])+1 < calendar.monthrange(end_year, end_month)[1]:
          end_day = int(Calendar.dateLabels[6])+1
      else:
          end_day = 1
          end_month = 1 + (end_month % 12)
          if end_month == 1:
              end_year = end_year + 1
      return start_year, start_month, start_day, end_year, end_month, end_day
    def query(self, week_offset):
        offset_day = self.day + week_offset*7
        
        # determine what the next and previous months are
        next_month = (self.month % 12) + 1
        if self.month - 1 != 0:
            prev_month = self.month - 1
        else:
            prev_month = 12

        # determine if we are at the edge of a year
        if next_month == 1:
            next_year = self.year + 1
        else:
            next_year = self.year
        if prev_month == 12:
            prev_year = self.year - 1
        else:
            prev_year = self.year
        

        # number of days in month and which day of the week was the first day of the month
        month_range = calendar.monthrange(self.year, self.month)[1]
        first_of_month = calendar.monthrange(self.year, self.month)[0]

        # current day (e.g. mon = 0, tues = 1, etc.)
        current_day = datetime.date.weekday(datetime.date.today())

        # months covered by current week
        months = [self.month]

        for i in range(7):
            dom = offset_day - current_day + i
            if dom <= 0:
                self.monthLabels[i] = prev_month
                months = [prev_month, self.month]
                dom = calendar.monthrange(prev_year, prev_month)[1] + dom
            elif dom > month_range:
                self.monthLabels[i] = next_month
                months = [self.month, next_month]
                dom = dom - month_range
            else:
                self.monthLabels[i] = self.month

            self.dateLabels[i] = '%i' % dom
            #self.monthLabels[i] = '%i'% if dom < 15 then Calendar.monthNamesmonths[1] else months[2]

        # week is entirely in next month
        if offset_day - month_range - current_day > 1:
            months = [next_month]
            for i in range(len(self.monthLabels)):
                self.monthLabels[i] = next_month
                

        # week is entirely in previous month
        # note: the second comparison looks to see if going to the end of the week (in 6 - current_days days)
        #       will carry you into the following month 
        elif offset_day < 0 and 6 - current_day < abs(offset_day):
            months = [prev_month]
            for i in range(len(monthLabels)):
                monthLabels[i] = prev_month

        return months, self.year

class ScheduleGrid(wx.grid.Grid):
    week_offset = 0
    cellShades = [(255, 255, 255, 255),
                  (215, 255, 215, 255),
                  (180, 255, 180, 255),
                  (120, 255, 120, 255),
                  ( 0 , 240,  00, 255),
                  (  0, 215,   0, 255),
                  (  0, 150,   0, 255)]
    colLabels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    hours= range(0,24)
    incr = range(0,31,30)
    eventsByHalfHour = {}
    shifts = []
    cellsChanged = []
    rowLabels = ["%d:%02d" % (x,y) for x in hours for y in incr]
    


    def __init__(self, parent, id, log, sidebar, gcal):
        wx.grid.Grid.__init__(self, parent, -1, size=(670, 660))
        self.log = log
        self.sidebar = sidebar
        self.parent = parent
        self.gcal = gcal
        cursize = self.GetSizeTuple()
        bestsize = self.GetBestSizeTuple()
        minw = self.GetMinWidth()
        wx.grid.EVT_GRID_CELL_LEFT_CLICK(self, self.CellClick)
        wx.grid.EVT_GRID_CELL_CHANGE(self, self.HandleCellChange)
        
        self.SetCellHighlightColour('White')
        self.DisableDragColSize()
        self.DisableDragRowSize()
        self.SetSelectionBackground((120,120,120))
        self.ImportEvents()
        self.ImportShifts()

        self.labels  = []
        self.buttons = []
        
        #rowLabels.append('23:59')


    def getAvailable(self, row, col):
        return self.eventsByHalfHour[(row,col)]

    def initializeSlot(self, key):
        '''index EventsByHalfHour by (row,col) and store list of all events at that time'''
        self.eventsByHalfHour[key] = []

    def setLabels(self):
        for col in range(7):
            self.SetColLabelValue(col, "%s\n%s" % (self.colLabels[col],
                                                   Calendar.dateLabels[col]))

        for row in range(0, 48, 2):
            self.SetRowLabelValue(row, self.rowLabels[row])

        for row in range(1, 49, 2):
            self.SetRowLabelValue(row, '')

    def getColor(self, i):
        '''returns the index of the closest color (keeps it in bounds)'''
        maxVal = len(self.cellShades)-1
        if i < 0: return self.cellShades[0]
        elif i > maxVal: return self.cellShades[maxVal]
        else: return self.cellShades[i]
        
    def increaseShade(self, cell):
        row, col = cell
        currentColor = self.GetCellBackgroundColour(row, col)
        currentColorIndex = self.cellShades.index(currentColor)
        newColor = self.getColor(currentColorIndex+1)
        self.SetCellBackgroundColour(row, col, newColor)
        
    def ClearShading(self):
        for col in range(0,7):
            for row in range(0,49):
                self.SetCellBackgroundColour(row, col, (255,255,255,255))
        #self.log.write("shading clear\n")
                
    def TimeToRow(self, time):
        try:
          row = self.rowLabels.index(time)
        except:
            pass
            #print time
        return row
    
    def RowToTime(self, row):
        return self.rowLabels[row]

    def ColToDay(self, col):
        return self.colLabels[col]

    def nextRow(self, row):
        return row + 1
    
    def HandleCellChange(self, evt):
        row = evt.GetRow()
        col = evt.GetCol()
        self.RecordCellChange(row, col)
        
    def RecordCellChange(self, row, col):
        self.log.write("Change recorded in slot %s %s\n" % 
                        ( self.ColToDay(col), self.RowToTime(row) ))
        if (row, col) not in self.cellsChanged:
            self.cellsChanged.append((row, col))
        #print self.cellsChanged
    
    def WriteToCell(self, row, col, user):
        self.SetCellValue(row, col, user)
        self.RecordCellChange(row, col)
    
    def CellClick(self, event):
        row = event.GetRow()
        col = event.GetCol()
        
        if (row, col) in self.eventsByHalfHour:
          self.log.write("Availabilities for %s %s:\n" %
                       (self.colLabels[col], self.rowLabels[row]))
          for ev in self.eventsByHalfHour[(row,col)]:
            self.log.write("  %s %s-%s\n" % 
                           (ev['user'], ev['start']['time'], ev['end']['time']))
        else:
            self.log.write("No employees available on (%s %s)\n" %
                       (self.colLabels[col], self.rowLabels[row]))
        if event.Selecting:
            self.ClearSelection()
        self.SetGridCursor(row, col)
        self.Refresh()
        self.DrawShiftPicker(row, col)
        
    def DrawShiftPicker(self, row, col):
        for label in self.labels:
            label.Destroy()
        for button in self.buttons:
            button.Destroy()
        self.labels  = []
        self.buttons = []
        self.shiftvalues = []
        self.sidebar.Refresh()
        self.buttonDefs = {}
        #pos x, pos y
        #siz x, siz y
        dayTitle  = wx.StaticText(self.sidebar, -1, "%s %s" % (self.ColToDay(col), self.RowToTime(row)),
                                    (10, 10), (100, 20), 
                                    style=wx.ALIGN_CENTRE)#|wx.ST_NO_AUTORESIZE)
                                    
        dayTitle_font = wx.Font(16, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, u'Candara')
        dayTitle.SetFont(dayTitle_font)
        
        ishift = 800
        if (row, col) in self.eventsByHalfHour:
            for ev in self.eventsByHalfHour[(row, col)]:
                ishift += 1
                tempLbl = wx.StaticText(self.sidebar, -1, " %s      %s-%s" % (ev['user'], ev['start']['time'], ev['end']['time']),
                                        (10,53+len(self.labels)*40),
                                        (115,15)
                                        )
                if ev['user'] == self.GetCellValue(row, col):
                  tempLbl.SetForegroundColour( (0,150,00,255) )
                  tempLbl.SetBackgroundColour( (255,255,255,255) )
                self.labels.append(tempLbl)
                self.buttonDefs[ishift] = (row, col, ev['user'])
                tempBtn = wx.Button(self.sidebar, ishift, "Choose",
                                    (140,50+len(self.buttons)*40),
                                    (50,20)
                                    )
                                    
                self.sidebar.Bind(wx.EVT_BUTTON, self.OnShiftClick, tempBtn)
                self.buttons.append(tempBtn)
            #endfor
            #draw "clear" button
            ishift += 1
            self.buttonDefs[ishift] = (row, col, "")
            clearBtn = wx.Button(self.sidebar, ishift, "Clear",
                                    (140,50+len(self.buttons)*40),
                                    (50,20)
                                    )
            self.sidebar.Bind(wx.EVT_BUTTON, self.OnShiftClick, clearBtn)
            self.buttons.append(clearBtn)
            #append day label
            self.labels.append(dayTitle)
           #print self.buttonDefs
    
    def OnShiftClick(self, evt):
        #needs row, col, and user
        #print "in onshiftclick:", evt.GetId()
        row, col, user = self.buttonDefs[evt.GetId()]
        
        self.WriteToCell(row, col, user)
        self.DrawShiftPicker(row, col)
        
    def ClearEvents(self):
        self.events = []
        self.eventsByHalfHour = {}
        #self.log.write("event cache cleared\n")

    def ClearShifts(self):
        for sh in self.shifts:
            currentCol = sh['start']['day']
            currentTime = sh['start']['time']
            currentRow = self.TimeToRow(currentTime)
            self.SetCellValue(currentRow, currentCol, "")
        self.shifts = []
        for row, col in self.cellsChanged:
            self.SetCellValue(row, col, "")
        self.cellsChanged = []
        
    def ImportShifts(self):
      self.setLabels()
      self.ClearShifts()
      months, year = Calendar().query(self.week_offset)
      YMDVals = Calendar().start_end_YMD(months, year)
      start_year, start_month, start_day, end_year, end_month, end_day = YMDVals
      shifts = self.parent.gcal.acquireEmployeeEvents('',
                                       'work',
                                       talkToGoogle.timeToString(datetime.datetime(start_year,start_month,start_day,0,0,0),4),
                                       talkToGoogle.timeToString(datetime.datetime(end_year,end_month,end_day,0,0,0),4))
      for shift in shifts:
          #subtract 1 to go from 1-7 to 0-6 for indexing
          start = {"day":shift[3][0].isoweekday()-1, "time":"%s:%02d" % (shift[3][0].hour, shift[3][0].minute)}
          end   = {"day":shift[4][0].isoweekday()-1, "time":"%s:%02d" % (shift[4][0].hour, shift[4][0].minute)}
          shift = {"start":start, "end": end, "user":shift[0]}
          #self.log.write("user: %s " % shift['user'])
          #self.log.write("start (%s, %s) " % (shift['start']['day'], shift['start']['time']))
          #self.log.write("end (%s, %s)\n" % (shift['end']['day'], shift['end']['time']))
          self.shifts.append(shift)
      #self.log.write("======\n")
      self.log.write( "%d shifts total.\n" % len(shifts))
      
    def ImportEvents(self ):
      self.setLabels()
      self.ClearEvents()
      months, year = Calendar().query(self.week_offset)
      YMDVals = Calendar().start_end_YMD(months, year)
      start_year, start_month, start_day, end_year, end_month, end_day = YMDVals
      events = self.parent.gcal.acquireEmployeeEvents('',
                                       'available',
                                       talkToGoogle.timeToString(datetime.datetime(start_year,start_month,start_day,0,0,0),4),
                                       talkToGoogle.timeToString(datetime.datetime(end_year,end_month,end_day,0,0,0),4))

      for event in events:
          #later:check that event type is "available" and not "work"
          start = {"day":event[3][0].isoweekday()-1, "time":"%s:%02d" % (event[3][0].hour, event[3][0].minute)}
          end   = {"day":event[4][0].isoweekday()-1, "time":"%s:%02d" % (event[4][0].hour, event[4][0].minute)}
          ev = {"start":start, "end": end, "user":event[0]}
          #self.log.write("user: %s " % ev['user'])
          #self.log.write("start (%s, %s) " % (ev['start']['day'], ev['start']['time']))
          #self.log.write("end (%s, %s)\n" % (ev['end']['day'], ev['end']['time']))
          self.events.append(ev)
      #self.log.write("======\n")
      self.log.write( "%d employee-availabilities loaded.\n" % len(events))

    def WriteShifts(self):
        for sh in self.shifts:
            currentCol = sh['start']['day']
            currentTime = sh['start']['time']
            currentRow = self.TimeToRow(currentTime)
            while currentRow != self.TimeToRow(sh['end']['time']):
                cell = (currentRow, currentCol)
                self.SetCellValue(cell[0], cell[1], sh['user'])
                currentRow = self.nextRow(currentRow)
                if currentRow > len(self.rowLabels): 
                  break
        self.ForceRefresh()
        self.Refresh()
        self.Update()
        
    def ShadeCells(self):
        for ev in self.events:
            currentCol = ev['start']['day']
            currentTime = ev['start']['time']
            currentRow = self.TimeToRow(currentTime)
            while currentRow != self.TimeToRow(ev['end']['time']):
                cell = (currentRow, currentCol)
                if cell not in self.eventsByHalfHour:
                    self.initializeSlot(cell)
                self.eventsByHalfHour[cell].append(ev)
                #print "%s added to %s" % (ev, cell)
                self.increaseShade(cell)
                currentRow = self.nextRow(currentRow)
                if currentRow > len(self.rowLabels): 
                  break
        self.ForceRefresh()
        self.Refresh()
        self.Update()
        
    def SaveSchedule(self):
        months, year = Calendar().query(self.week_offset)
        self.log.write("Saveing %s shifts...\n" % len(self.cellsChanged))
        for row, col in self.cellsChanged:
                hour, minute = self.RowToTime(row).strip().split(':')
                start = datetime.datetime(int(year), 
                                          int(Calendar.monthLabels[col]), 
                                          int(Calendar.dateLabels[col]), 
                                          int(hour), 
                                          int(minute))
                hour, minute = self.RowToTime(row+1).strip().split(':')
                end = datetime.datetime(int(year), 
                                          int(Calendar.monthLabels[col]), 
                                          int(Calendar.dateLabels[col]), 
                                          int(hour), 
                                          int(minute))
                assigned = self.GetCellValue(row, col)
                existing = self.parent.gcal.acquireEmployeeEvents('',
                                "work",
                                talkToGoogle.timeToString(start, 4),
                                talkToGoogle.timeToString(end  , 4))
                if assigned:
                    #username is event[0], href is event[2]
                    add_event = 0
                    for event in existing:
                        if assigned != existing:
                           self.parent.gcal.removeEvent_href(event[2])
                           add_event = 1
                    if add_event or len(existing) == 0:
                        self.parent.gcal.addEvent(assigned, talkToGoogle.timeToString(start, 4),
                                           talkToGoogle.timeToString(end  , 4), "work")
                else:
                    #now blank => remove existing
                    for event in existing:
                        self.parent.gcal.removeEvent_href(event[2])
        if len(self.cellsChanged) != 0:
          self.log.write("%s shifts saved successfully!\n" % len(self.cellsChanged))
        else:
          self.log.write("No shifts to save.\n")
                           
        
    def UpdateCells(self):
        self.log.write("=====\n")
        self.ClearShading()
        self.ClearEvents()
        self.ClearShifts()
        self.ImportEvents()
        self.ImportShifts()
        self.ShadeCells()
        self.WriteShifts()
        self.setLabels()
        self.ForceRefresh()
        
        
class SashWindowLayout(wx.Panel):
    def __init__(self, parent, gcal):
        wx.Panel.__init__(self, parent, -1)
        self.parent = parent
        self.gcal = gcal
        winids = []

        #top
        toolbar = wx.SashLayoutWindow(
            self, -1, wx.DefaultPosition, (200, 30), 
            wx.NO_BORDER|wx.SW_3D
            )

        toolbar.SetDefaultSize((1000, 40))
        toolbar.SetOrientation(wx.LAYOUT_HORIZONTAL)
        toolbar.SetAlignment(wx.LAYOUT_BOTTOM)
        toolbar.SetBackgroundColour(wx.Colour(160, 160, 160))
        toolbar.SetSashVisible(wx.SASH_TOP, False)

        refresh = wx.Button(toolbar, 11, "Refresh", (500, 10))
        self.Bind(wx.EVT_BUTTON, self.OnRefresh, refresh)
        refresh.SetDefault()
        refresh.SetSize(refresh.GetBestSize())
        
        save = wx.Button(toolbar, 12, "Save", (300, 10))
        self.Bind(wx.EVT_BUTTON, self.OnSave, save)
        save.SetDefault()
        save.SetSize(save.GetBestSize())
        
        self.back = wx.Button(toolbar, 13, "<<", (10, 10))
        self.Bind(wx.EVT_BUTTON, self.OnBack, self.back)
        self.back.SetDefault()
        self.back.SetSize(self.back.GetBestSize())
        
        self.next = wx.Button(toolbar, 14, ">>", (780, 10))
        self.Bind(wx.EVT_BUTTON, self.OnNext, self.next)
        self.next.SetDefault()
        self.next.SetSize(self.next.GetBestSize())
        
        self.toolbar = toolbar
        winids.append(toolbar.GetId())

        # bottom window for a message log
        bottomwin = wx.SashLayoutWindow(
                self, -1, wx.DefaultPosition, (200, 30), 
                wx.NO_BORDER|wx.SW_3D
                )
        bottomwin.SetDefaultSize((1000, 100))
        bottomwin.SetOrientation(wx.LAYOUT_HORIZONTAL)
        bottomwin.SetAlignment(wx.LAYOUT_BOTTOM)
        bottomwin.SetBackgroundColour(wx.Colour(0, 0, 255))
        bottomwin.SetSashVisible(wx.SASH_TOP, False)

        self.bottomWindow = bottomwin
        winids.append(bottomwin.GetId())
        
        logtext = wx.TextCtrl(bottomwin, -1,
                        "",
                       size=(200, 100), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
        logtext.SetEditable(False)
        self.log = logtext
        self.log.write("Successfully authenticated\n")

        # Sidebar window
        sidebar = wx.SashLayoutWindow(
                self, -1, wx.DefaultPosition, (200, 30), 
                wx.NO_BORDER|wx.SW_3D
                )

        sidebar.SetDefaultSize((200, 1000))
        sidebar.SetOrientation(wx.LAYOUT_VERTICAL)
        sidebar.SetAlignment(wx.LAYOUT_RIGHT)
        sidebar.SetBackgroundColour(wx.Colour(200, 200, 200))
        sidebar.SetSashVisible(wx.SASH_LEFT, False)
        
        #bsizer.Add(t, 0, wx.TOP|wx.LEFT, 10)
        #border = wx.BoxSizer()
        #border.Add(bsizer, 1, wx.EXPAND|wx.ALL, 25)
        #self.SetSizer(border)

        self.sidebar = sidebar
                
        winids.append(sidebar.GetId())

        self.grid = ScheduleGrid(self, 10, self.log, self.sidebar,self.gcal)
        self.grid.CreateGrid(48,7)
        self.grid.setLabels()
        self.grid.DisableDragColSize()
        self.grid.DisableDragRowSize()
        self.grid.ShadeCells()
        self.grid.WriteShifts()

        # will occupy the space not used by the Layout Algorithm
        self.remainingSpace = wx.Panel(self, -1, style=wx.SUNKEN_BORDER)

        self.Bind(
            wx.EVT_SASH_DRAGGED_RANGE, self.OnSashDrag,
            id=min(winids), id2=max(winids)
            )

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.MonthDisplay()

    def OnRefresh(self, event):
        self.grid.UpdateCells()
        self.DestroyMonthDisplay()
        self.MonthDisplay()
        
    def OnSave(self, event):
        self.grid.SaveSchedule()

    def OnNext(self, event):
        if self.grid.week_offset < 2:
            self.grid.week_offset += 1
            self.back.Show(True)
            #print self.grid.week_offset
            self.grid.UpdateCells()
            self.DestroyMonthDisplay()
            self.MonthDisplay()

            if self.grid.week_offset == 2:
                self.next.Show(False)
        
    def OnBack(self, event):
        
        if self.grid.week_offset > -2:
            self.grid.week_offset -= 1
            self.next.Show(True)
            #print self.grid.week_offset
            self.grid.UpdateCells()
            self.DestroyMonthDisplay()
            self.MonthDisplay()
            
            if self.grid.week_offset == -2:
                self.back.Show(False)

    def OnSashDrag(self, event):
        if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
            #self.log.write('Drag is out of range\n')
            return

        eobj = event.GetEventObject()

        if eobj is self.sidebar:
            #self.log.write('sidebar received drag event\n')
            self.sidebar.SetDefaultSize((event.GetDragRect().width, 1000))

        elif eobj is self.bottomWindow:
            #self.log.write('bottomwin received drag event\n')
            self.bottomWindow.SetDefaultSize((1000, event.GetDragRect().height))

        wx.LayoutAlgorithm().LayoutWindow(self, self.remainingSpace)
        self.remainingSpace.Refresh()
        self.grid.ForceRefresh()
        
        
    def OnSize(self, event):
        wx.LayoutAlgorithm().LayoutWindow(self, self.remainingSpace)

    def MonthDisplay(self):
        months, year = Calendar().query(self.grid.week_offset)
        try:
            months_str = Calendar.monthNames[months[0]] + " / " + Calendar.monthNames[months[1]]
        except IndexError:
            months_str = Calendar.monthNames[months[0]]
        #str_length = len(months_str)
        
        font_size = 16
        month_font = wx.Font(font_size, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, u'Candara')

        self.month = wx.StaticText(self.toolbar, -1, "%s" % (months_str), (385, 10), (400, 100), style=wx.ALIGN_CENTRE)
        self.month.SetFont(month_font)
        #self.month.MoveXY(670/2 - str_length/2*font_size/2, 50)


    def DestroyMonthDisplay(self):
        self.month.Destroy()

class LoginDialog(wxDialog):
    def ShouldPreventAppExit():
        return False
        
    def __init__(self, parent, id=-1, title="Login",
                 pos=wxDefaultPosition,
                 size=wxSize(250, 150)):
        wxDialog.__init__(self, parent, id, title, pos, size)
        wxStaticText(self, -1, 'Please type your user name and password.',
                     wxPoint(15, 5))
        wxStaticText(self, -1, 'User name: ', wxPoint(20, 30))
        wxStaticText(self, -1, 'Password: ', wxPoint(20, 55))
        self.nameBox = wxTextCtrl(self, -1, '', wxPoint(80,30),
                                  wxSize(120, -1))
        self.passwordBox = wxTextCtrl(self, -1, '', wxPoint(80,55),
                                 wxSize(120, -1), style=wxTE_PASSWORD)
        wxButton(self, wxID_OK,     ' OK ', wxPoint(35, 90), wxDefaultSize).SetDefault()
        wxButton(self, wxID_CANCEL, ' Cancel ', wxPoint(135, 90),
                 wxDefaultSize)

    def GetUser(self):
        val = self.ShowModal()
        if val == wxID_OK:
            local_username = self.nameBox.GetValue()
            local_password = self.passwordBox.GetValue()
            return [local_username, local_password]
        elif val == wxID_CANCEL:
            sys.exit(0)
        else:
            return ['','']

class SizedWindow(wx.Frame):
    gcal = talkToGoogle.talkToGoogle()
    def __init__(self, parent, id, title):
        main = wx.Frame.__init__(self, parent, id, title, size=(880, 840))
        login = LoginDialog(main)
        username, password = login.GetUser()
        if not self.gcal.authenticate(username,password):
            sys.exit(0)
        window=SashWindowLayout(self, self.gcal)
        self.Show(True)
        
        EVT_CLOSE(self, self.OnClose)
    
    def OnClose(self, event):
        self.Destroy()
        print "Goodbye!"
        sys.exit(0)
        

if __name__ == "__main__":
    app = wx.App(0)
    window=SizedWindow(None, -1, "Schedule View")
    window.Show()
    app.MainLoop()
